<?php
/**
 * crcl/base
 *
 * Copyright 2013 CRCL - André Sabosch - info@crcl.de
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace crcl\base\persistance\item;

interface IMysql
{
}

class ContainerMysql extends Base implements IMysql
{
  public function save()
  {
    if ($this->oItem->isDirty())
    {
      $aData = $this->oItem->toArrayDirty();

      if (\is_null($this->oItem->id->get()))
      {
        $this->oDatabase->insert($this->oDsn->getTable(), $aData);
        $id = $this->oDatabase->getLastInsertedId();
        $this->oItem->id->set($id);
        $this->oItem->commit();
      }
      else
      {
        $this->oDatabase->updateById($this->oDsn->getTable(), $aData, $this->oItem->id->get());
        $this->oItem->commit();
      }
    }
  }

  public function delete()
  {
    if (\is_null($this->oItem->id->get()))
    {
      throw new Exception('Item not persisted.',
        Exception::ERROR_MYSQL_NOTPERSISTED,
        array('fields' => $this->oItem->toArray()));
    }
    $this->oDatabase->deleteById($this->oDsn->getTable(), $this->oItem->id->get());
  }

  public function load($id = \NULL)
  {
    if (\is_null($id))
    {
      $id = $this->oItem->id->get();
    }
    $aFields = $this->oItem->getFieldnames();
    $aFields[] = 'id';
    $aData = $this->oDatabase->selectById(
      $this->oDsn->getTable(), $aFields, $id)->getAsRow();

    $this->oItem->fromArray($aData);

    return $this->oItem;
  }
}